package com.ims.listenser;

import com.alibaba.fastjson.JSONObject;
import com.ims.pojo.Device;
import com.ims.service.DeviceService;
import com.ims.util.DecryptUtil;
import io.github.majusko.pulsar.annotation.PulsarConsumer;
import io.github.majusko.pulsar.constant.Serialization;
import org.apache.pulsar.client.api.SubscriptionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class DeviceInfoListener {

    @Autowired
    private DeviceService deviceService;

    @PulsarConsumer(topic = "deviceinfo",  // 订阅topic名称
            subscriptionName = "ims_server", // 订阅名称
            serialization = Serialization.JSON, // 序列化方式
            subscriptionType = SubscriptionType.Shared, // 订阅模式，默认为独占模式
            consumerName = "ims_server", // 消费者名称
            maxRedeliverCount = 5 // 最大重试次数
//            deadLetterTopic = "sub_topic1-DLQ" // 死信topic名称
    )
    public void topicConsume(byte[] encryptMsg) {
        // TODO process your message
        String decryptMsg = DecryptUtil.sm2Decrypt(new String(encryptMsg));

        JSONObject deviceInfo = JSONObject.parseObject(decryptMsg);
        String deviceId = deviceInfo.get("device_id").toString();
        String deviceName = deviceInfo.get("device_name").toString();
        String eventTime = deviceInfo.get("event_time").toString();

        Device device = new Device();
        device.setDeviceId(deviceId);
        device.setDeviceName(deviceName);
        device.setDeviceInfo(deviceInfo.toString());
        device.setEventTime(eventTime);

        deviceService.add(device);

        System.out.println("Received a new message. content: [" + decryptMsg + "]");
        // 如果消费失败，请抛出异常，这样消息会进入重试队列，之后可以重新消费，直到达到最大重试次数之后，进入死信队列。前提是要创建重试和死信topic
    }
}
